package com.fs.user.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 全局编码处理器
 */
@WebFilter(filterName = "EncodingFilter",value = "/*")
public class EncodingFilter implements Filter {
    @Override
    public void destroy() {
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest request = (HttpServletRequest)req;
        HttpServletResponse response = (HttpServletResponse)resp;
        if(request.getMethod().equals("POST")){
            request.setCharacterEncoding("UTF-8"); //post请求编码处理
        }
        //图片,css.js 不应该设置text/html;charset=utf-8, 动态资源text/html;charset=utf-8  只针对于servlet设置
        //response.setContentType("text/html;charset=utf-8"); //响应编码
        String requestURI = request.getRequestURI();

        if(!requestURI.contains(".")){
            response.setContentType("text/html;charset=utf-8");
        }
        //System.out.println("url:"+request.getRequestURL());
        //System.out.println("ServletPath:"+request.getServletPath());
        chain.doFilter(request, response); //放行
    }

    @Override
    public void init(FilterConfig config) throws ServletException {

    }

}
